import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class DmTool extends Thread {

    public DmTool(){

    }

    DmjMain dmjMain;
    String roomid;

    public void getRoomid() throws Exception {
        String res = HttpClient.getInstance().doGet("https://api.live.bilibili.com/room/v1/Room/room_init?id="+roomid);
        roomid = JSONObject.parseObject(res).getJSONObject("data").getString("room_id");
    }

    public JSONArray getDm() throws Exception {
        Map data = new HashMap<String,String>();
        data.put("roomid", roomid);
        String res = HttpClient.getInstance().doPost("https://api.live.bilibili.com/ajax/msg",data);
        return JSONObject.parseObject(res).getJSONObject("data").getJSONArray("room");
    }

    public void startAndGetDm() throws Exception {
        dmjMain.linkBtn.setDisable(true);
        getRoomid();
        JSONArray dmJsonArray;
        while (dmjMain.isGetDm){
            dmJsonArray = new JSONArray();
            try {
                dmJsonArray = getDm();
            } catch (Exception e){
                dmjMain.newLogCallback("获取弹幕错误:",e.getMessage());
            }
            JSONObject dmJson;
            for (int i = 0;i < dmJsonArray.size();i++){
                dmJson = dmJsonArray.getJSONObject(i);
                if (!dmJsonInDmJsonAttay(dmJson,dmjMain.dmJsonArray)){
                    dmjMain.newDmCallback(dmJson);
                    dmjMain.dmJsonArray.add(dmJson);
                }
            }
            Thread.sleep(500);
        }
        dmjMain.linkBtn.setDisable(false);
    }

    public Boolean dmJsonInDmJsonAttay(JSONObject jsonObject , JSONArray jsonArray){
        for (int i = 0 ;i<jsonArray.size();i++){
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            if (jsonObject.equals(jsonObject1)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void run() {
        try {
            startAndGetDm();
        } catch (Exception e) {
            dmjMain.newLogCallback("获取弹幕错误:",e.getMessage());
            dmjMain.isGetDm = false;
            dmjMain.linkBtn.setDisable(false);
        }
    }

}
